/**
 * 
 */
package fr.isima.tools;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FilePermission;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.util.Log;

import com.google.android.maps.GeoPoint;

/**
 * @author vincent
 */
public class KMLGenerator
{

    // Singleton
    private static final String HEADER = "<?xml version=\"1.0\" encoding=\"UTF-8\"?> <kml xmlns=\"http://earth.google.com/kml/2.2\"><Document><name>%s</name>";

    private static final String ITEM   = "<Placemark><name>%d</name><description>%s</description><Point><coordinates>%f,%f,0</coordinates></Point></Placemark>";

    private static final String FOOTER = "</Document></kml>";

    private static final String TAG    = "KMLGenerator";

    private List<GeoPoint>      trackPoints;

    private static KMLGenerator instance;

    public static KMLGenerator getGenerator()
    {
        if (instance == null)
        {
            instance = new KMLGenerator();
        }

        return instance;
    }

    private KMLGenerator()
    {
        trackPoints = new ArrayList<GeoPoint>();
    }

    public void addPoint(GeoPoint point)
    {
        trackPoints.add(point);
    }

    public void removePoinst()
    {
        trackPoints.clear();
    }

    public boolean generate(String name)
    {
        boolean success = false;
        String directoryName = "/data/data/fr.isima/tracks/";
        String pathName = directoryName + name + ".kml";
        File directory = new File(directoryName);
        File file = new File(pathName);
        try
        {
            if (!directory.exists())
            {
                directory.mkdir();
            }

            if (!file.exists())
            {
                FilePermission perm = new FilePermission(pathName, "write");
                file.createNewFile();
                
                perm = null;
            }
            BufferedWriter out = new BufferedWriter(new FileWriter(file), 256);

            out.append(String.format(HEADER, name));

            int i = 0;
            for (GeoPoint point : trackPoints)
            {

                out.append(String.format(ITEM, i++, name, point
                        .getLongitudeE6() / 1E6, point.getLatitudeE6() / 1E6));
            }

            out.append(FOOTER);
            out.flush();
            out.close();

            out = null;
            file = null;
            success = true;
        }
        catch (IOException e)
        {
            Log.d(TAG, e.getMessage());
        }

        return success;
    }

}
